package cn.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zhentao.pojo.TPurchaseOrder;
import cn.zhentao.service.TPurchaseOrderService;
import cn.zhentao.mapper.TPurchaseOrderMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
* @author 郭永辉
* @description 针对表【t_purchase_order(购车订单表（订单页、订单详情）)】的数据库操作Service实现
* @createDate 2025-09-03 14:23:10
*/
@Service
public class TPurchaseOrderServiceImpl extends ServiceImpl<TPurchaseOrderMapper, TPurchaseOrder>
        implements TPurchaseOrderService {

    @Override
    @Transactional
    public Map<String, Object> createOrder(TPurchaseOrder order) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 生成唯一订单编号
            String orderNo = "PO" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
            order.setOrderNo(orderNo);

            // 保存订单
            boolean success = save(order);
            if (success) {
                result.put("code", 200);
                result.put("message", "订单创建成功");
                result.put("orderId", order.getId());
                result.put("orderNo", orderNo);
            } else {
                result.put("code", 500);
                result.put("message", "订单创建失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "订单创建异常: " + e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public List<TPurchaseOrder> getOrdersByStatusAndBuyer(byte[] statusList, Long buyerId) {
        QueryWrapper<TPurchaseOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("order_status", statusList);
        if (buyerId != null) {
            queryWrapper.eq("buyer_id", buyerId);
        }
        queryWrapper.orderByDesc("create_time");
        return list(queryWrapper);
    }

    @Override
    @Transactional
    public Map<String, Object> cancelOrder(Long orderId, String cancelReason) {
        Map<String, Object> result = new HashMap<>();
        try {
            TPurchaseOrder order = getById(orderId);
            if (order == null) {
                result.put("code", 404);
                result.put("message", "订单不存在");
                return result;
            }

            // 检查是否可以取消（仅允许取消待支付状态的订单）
            byte currentStatus = order.getOrderStatus().byteValue();
            if (currentStatus != 1 && currentStatus != 2) {
                result.put("code", 400);
                result.put("message", "只有待支付状态的订单可以取消");
                return result;
            }

            // 更新订单状态为取消
            order.setOrderStatus((int) 0);
            order.setCancelReason(cancelReason);
            //order.setCancelTime(new Date());
            boolean success = updateById(order);

            if (success) {
                result.put("code", 200);
                result.put("message", "订单已取消");
            } else {
                result.put("code", 500);
                result.put("message", "取消订单失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "取消订单异常: " + e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public List<TPurchaseOrder> getOrdersByStatusAndUser(byte status, Long buyerId, Long sellerId) {
        QueryWrapper<TPurchaseOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", status);

        // 根据传入的ID筛选（买家或卖家）
        if (buyerId != null) {
            queryWrapper.eq("buyer_id", buyerId);
        }
        if (sellerId != null) {
            queryWrapper.eq("seller_id", sellerId);
        }

        queryWrapper.orderByDesc("create_time");
        return list(queryWrapper);
    }

    @Override
    @Transactional
    public Map<String, Object> updateOrderAfterPayment(Long orderId, byte targetStatus, Date payTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            TPurchaseOrder order = getById(orderId);
            if (order == null) {
                result.put("code", 404);
                result.put("message", "订单不存在");
                return result;
            }

            // 检查状态是否合法
            byte currentStatus = order.getOrderStatus().byteValue();
            if (!isValidStatusTransition(currentStatus, targetStatus)) {
                result.put("code", 400);
                result.put("message", "不合法的状态转换");
                return result;
            }

            // 更新订单状态和支付时间
//            order.setOrderStatus((int) targetStatus);
//            if (targetStatus == 2) { // 付定金后→待付全款
//                order.setDepositPayTime(payTime); // 付定金后→待付全款
//            } else if (targetStatus == 3) { // 付全款后→待交付
//                order.setFullPayTime(payTime);
//            }

            boolean success = updateById(order);
            if (success) {
                result.put("code", 200);
                result.put("message", "支付成功，订单已更新");
            } else {
                result.put("code", 500);
                result.put("message", "订单更新失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "支付处理异常: " + e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    @Transactional
    public Map<String, Object> updateOrderStatus(Long orderId, byte status) {
        Map<String, Object> result = new HashMap<>();
        try {
            TPurchaseOrder order = getById(orderId);
            if (order == null) {
                result.put("code", 404);
                result.put("message", "订单不存在");
                return result;
            }

            // 检查状态是否合法（仅允许对待交付状态(3)更新为已完成(4)）
            byte currentStatus = order.getOrderStatus().byteValue();
            if (currentStatus != 3 || status != 4) {
                result.put("code", 400);
                result.put("message", "不合法的状态转换");
                return result;
            }

            // 更新订单状态
            order.setOrderStatus((int) status);
            //order.setCompleteTime(new Date());
            boolean success = updateById(order);

            if (success) {
                result.put("code", 200);
                result.put("message", "订单已标记为完成");
            } else {
                result.put("code", 500);
                result.put("message", "订单状态更新失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "更新订单状态异常: " + e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 检查状态转换是否合法
     */
    private boolean isValidStatusTransition(byte current, byte target) {
        // 允许的状态转换: 1→2（待付定金→待付全款），2→3（待付全款→待交付）
        return (current == 1 && target == 2) || (current == 2 && target == 3);
    }
}




